<script>
// 账单模态表单页
Vue.component('record-form', {
    template: `
<el-dialog title="账单修改" :visible.sync="dialogShow" width="1080px" @close="closeModal">
        <el-form :inline="true" :model="tallyRecordEditForm" :rules="tallyFormRules" class="form-inline recordForm">
            <el-row>
            <el-col :span="12">
                    <el-form-item label="类型" prop="type">
                        <el-input placeholder="0.00" :disabled="true" :value="getTypeTxt(tallyRecordEditForm.type)"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="金额" prop="amount">
                        <el-input placeholder="0.00" :disabled="productListData.length > 0" v-model="tallyRecordEditForm.amount"> <template slot="append">元</template></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item v-if="tallyRecordEditForm.type == 10" label="分类">
                        <el-cascader
                     collapse-tags clearable
                     v-model="categorys"
                     :options="categoryListIn" />
                    </el-form-item>
                    <el-form-item v-if="tallyRecordEditForm.type == 20" label="分类">
                    <el-cascader
                     collapse-tags clearable
                     v-model="categorys"
                     :options="categoryListOut" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item prop="account_id">
                        <span slot="label">{{ tallyRecordEditForm.type == 30 ? "转出":"账户" }}</span>
                        <el-select placeholder="账户" clearable filterable default-first-option v-model="tallyRecordEditForm.account_id">
                            <el-option
                                    v-for="item in accountList"
                                    :key="item.id"
                                    :label="item.title"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item prop="account_dst_id" v-if="tallyRecordEditForm.type == 30">
                        <span slot="label">转入</span>
                        <el-select placeholder="转入账户" clearable filterable default-first-option v-model="tallyRecordEditForm.account_dst_id">
                            <el-option
                                    v-for="item in accountList"
                                    :key="item.id"
                                    :label="item.title"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item v-if="tallyRecordEditForm.type == 10" label="客户">
                        <el-select  placeholder="客户" clearable filterable default-first-option v-model="tallyRecordEditForm.store_id">
                            <el-option
                                    v-for="item in customList"
                                    :key="item.id"
                                    :label="item.title"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item v-if="tallyRecordEditForm.type == 20" label="供应商">
                        <el-select  placeholder="供应商" clearable filterable default-first-option v-model="tallyRecordEditForm.store_id">
                            <el-option
                                    v-for="item in gysList"
                                    :key="item.id"
                                    :label="item.title"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="员工">
                        <el-select  placeholder="员工" clearable filterable default-first-option v-model="tallyRecordEditForm.member_id" no-data-text="其他">
                            <el-option
                                    v-for="item in memberList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="项目">
                        <el-select  placeholder="项目" clearable filterable default-first-option v-model="tallyRecordEditForm.project_id">
                            <el-option
                                    v-for="item in projectList"
                                    :key="item.id"
                                    :label="item.title"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="时间" style="margin-right:0;">
                        <el-date-picker class="datePicker" v-model="tallyRecordEditForm.dateR" placeholder="选择日期" value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="备注">
                        <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 8}" maxlength="255" show-word-limit placeholder="备注" class="tallyMemoInput" v-model="tallyRecordEditForm.memo"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                <p style="margin-bottom: 10px;">
                    <el-link :underline="false" type="info"  @click="showImgUploadBox = !showImgUploadBox"><i class="el-icon-paperclip"></i>&nbsp;添加图片或附件 <i class="el-icon-arrow-down"></i></el-link>
                    <el-upload v-if="showImgUploadBox" accept="image/jpeg,image/gif,image/png,application/vnd.ms-excel,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/zip,application/rar,application/pdf" action="/api/upload/file" :headers="upHeaders"
                               :before-upload="recordFormFileBeforeUpload"
                               :file-list="recordFormEditFileList"
                               :on-success="recordFormEditFileUploadSuccess"
                               :on-remove="recordFormEditFileRemove"
                               list-type="picture-card" :limit="3">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </p>
                </el-col>
            </el-row>





</el-form>



            <el-table
              :data="productListData"
              style="width: 100%">
             <el-table-column
                prop="product_info"
                label="材料" >
                  <template slot-scope="scope">
                    <div>
                            <el-select

                        size="mini"
                        placeholder="全部材料"
                        :value="productListData[scope.$index]['title']"
                        filterable
                        default-first-option
                        @change="changeMaterial($event,scope.row,scope.$index)"
                    >
                    <el-option
                    v-for="item in materials"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id">
                    </el-option>
                    </el-select>
                    </div>
                  </template>
              </el-table-column>
            <el-table-column
                prop="spec"
                label="单位">
                <template slot-scope="scope">
                    <span>{{scope.row['spec']}}</span>
                  </template>
              </el-table-column>

              <el-table-column
                prop="cost_price"
                label="单价">
                <template slot-scope="scope">
                    <span>{{scope.row['cost_price']}}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="num"
                label="数量">
                <template slot-scope="scope">
                  <el-input v-model="productListData[scope.$index]['num']" size="mini" v-if="productListData[scope.$index]['material_id']" type="number" min="0" step="1" :max="calcMax(productListData[scope.$index]['pure_num'])" @blur="validNum($event,scope.$index)"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="money"
                label="金额">
                <template slot-scope="scope">
                      <el-input v-model="productListData[scope.$index]['money']" size="mini" v-if="productListData[scope.$index]['material_id']" type="number" min="0" step="0.01" @blur="validPrice($event,scope.$index)"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="opt"
                label="">
                <template slot-scope="scope">
                  <el-button type="info" icon="el-icon-delete" circle  @click="delProductRow(scope.$index)" size="mini"></el-button>
                </template>
              </el-table-column>
            </el-table>
            <p class="opt-row">
        <i class="el-icon-plus"></i>
        <el-button type="text" @click="addProductRow">添加一行</el-button>
        </p>
        <p class="t-r">
        金额合计：{{productTotalMoney}}
        </p>

            <el-row>
                <el-col :span="24">
                    <p style="text-align:center;margin-bottom: 20px;margin-top:20px">
                        <el-button type="success" @click="handleRecordEditForm"><i class="el-icon-upload"></i> 保 存</el-button>
                        <el-button @click="closeModal">取 消</el-button>
                    </p>
                </el-col>
            </el-row>

</el-dialog>
    `,
    props: ['dialog-show','form-row'],
    computed: {
        currentTallyId() {
            return this.$store.state.currentTallyId
        },
        currentTally () {
            return this.$store.state.currentTally
        },
        customList () {
            return this.$store.state.customList
        },
        gysList () {
            return this.$store.state.gysList
        },
        categoryListIn() {
            let options = []
            let origin_datas = this.$store.state.categoryListIn;
            for (let i=0;i<origin_datas.length;i++){
                if(origin_datas[i]['children']===undefined){
                    continue;
                }
                let itemData = {
                    'label':origin_datas[i]['title'],
                    'value':origin_datas[i]['id'],
                    'children':[]
                };
                for (let a = 0;a<origin_datas[i]['children'].length;a++){
                    let itemVItem = {
                        'label':origin_datas[i]['children'][a]['title'],
                        'value':origin_datas[i]['children'][a]['id'],
                    };
                    if(origin_datas[i]['children'][a]['children'] !== undefined){
                        itemVItem['children'] = [];
                        for (let z=0;z<origin_datas[i]['children'][a]['children'].length;z++){
                            itemVItem['children'].push({
                                'label':origin_datas[i]['children'][a]['children'][z]['title'],
                                'value':origin_datas[i]['children'][a]['children'][z]['id'],
                            });
                        }
                    }
                    itemData['children'].push(itemVItem);
                }
                options.push(itemData);
            }
            return options;
        },
        categoryListOut() {
            let options = []
            let origin_datas = this.$store.state.categoryListOut;
            for (let i=0;i<origin_datas.length;i++){
                if(origin_datas[i]['children']===undefined){
                    continue;
                }
                let itemData = {
                    'label':origin_datas[i]['title'],
                    'value':origin_datas[i]['id'],
                    'children':[]
                };
                for (let a = 0;a<origin_datas[i]['children'].length;a++){
                    let itemVItem = {
                        'label':origin_datas[i]['children'][a]['title'],
                        'value':origin_datas[i]['children'][a]['id'],
                    };
                    if(origin_datas[i]['children'][a]['children'] !== undefined){
                        itemVItem['children'] = [];
                        for (let z=0;z<origin_datas[i]['children'][a]['children'].length;z++){
                            itemVItem['children'].push({
                                'label':origin_datas[i]['children'][a]['children'][z]['title'],
                                'value':origin_datas[i]['children'][a]['children'][z]['id'],
                            });
                        }
                    }
                    itemData['children'].push(itemVItem);
                }
                options.push(itemData);
            }
            return options;
        },
        accountList() {
            return this.$store.state.accountList
        },
        projectList() {
            return this.$store.state.projectList
        },
        memberList() {
            return this.$store.state.memberList
        },
        materials(){
            return this.$store.state.materialList;
        }
    },
    watch: {
        dialogShow:{
            handler (newVal) {},
            deep:true,
            immediate: true
        },
        formRow: {
            handler (newVal) {
                this.categorys = newVal['category_route'].split(',');
                this.categorys.pop();
                this.categorys.shift();
                if(this.categorys[0] == 0){
                    this.categorys.shift();
                }



                this.tallyRecordEditForm = newVal
                this.productListData = newVal.material_json
                console.log(this.productListData)
                this.recordFormEditFileList=[]
                // 处理附件转换
                if(newVal.hasOwnProperty('attachment')) {
                    newVal.attachment.forEach(v=>{
                        this.recordFormEditFileList.push({
                            name:v.id,
                            url:v.file_name
                        })
                    })
                }
            },
            deep:true,
            immediate: true
        }
    },
    data:function(){
        return {
            productTotalMoney:0,
            productListData:[],
            showImgUploadBox:true,
            upHeaders:{
                token:loginToken
            },
            dialogVisible: false,
            dialogImageUrl: '',
            categorys:[],
            recordFormFileList: [],
            recordFormEditFileList: [],
            tallyRecordEditForm:{},
            tallyFormRules: {
                amount: [
                    { required: true, message: '请输入金额', trigger: 'blur' }
                ],
                account_id: [
                    { required: true, message: '请选择账户', trigger: 'blur' }
                ],
                account_dst_id: [
                    { required: true, message: '请选择转入账户', trigger: 'blur' }
                ],
                category_id: [
                    { required: true, message: '请选择类别', trigger: 'blur' }
                ],
            },
        }
    },
    methods:{
        calTotal() {
            let totalMoney = 0
            this.productListData.forEach((item) => {
                if(item['material_id']) {
                    totalMoney = totalMoney + parseFloat(item['money'])
                }
            })
            this.productTotalMoney = parseFloat(totalMoney).toFixed(2)
            this.tallyRecordEditForm.amount = this.productTotalMoney
        },
        validPrice(e,index){
            let number = this.productListData[index]['money']
            money = parseFloat(number).toFixed(2)
            this.productListData[index]['money'] = money
            this.calRowMoney(index)
        },
        changeMaterial(productId, row, index) {

            let that = this
            let item = this.materials.find((iv)=>{
                return iv.id === productId;
            });


            console.log(index)
            this.$set(this.productListData,index,{
                'title':item['title'],
                'material_id':item['id'],
                'spec':item['spec'],
                'cost_price':item['price'],
                'num':1
            })
            this.calRowMoney(index)

        },
        calcMax(num) {
            if(!num) return '';
            if(isNaN(num)) {
                return '';
            }else {
                return parseFloat(num)
            }
        },
        calRowMoney(index){
            let money = this.productListData[index]['money']
            let num = this.productListData[index]['num']
            let cost_price = (money / num ).toFixed(2);
            if(!isNaN(cost_price)){
                this.productListData[index]['cost_price'] = cost_price
            }
            this.calTotal()
        },
        validNum(e,index) {
            let number = this.productListData[index]['num']
            number = parseFloat(number).toFixed(2)
            this.productListData[index]['num'] = number
            this.calRowMoney(index)

        },
        addProductRow() {
            this.productListData.push({})
        },
        delProductRow(index)  {
            this.productListData.splice(index,1)
            this.calTotal()
        },
        closeModal(){
            this.$emit('modalClose')
        },
        recordFormFileBeforeUpload(file){
            console.log(file)
        },
        getTypeTxt(type) {
            if(type === 10) return '收入'
            if(type === 20) return '支出'
            if(type === 30) return '转账'
        },
        recordFormFileUploadSuccess(response, file, fileList){
            if(response.status === 'success') {
                file.url = response.data.url
                this.recordFormFileList.push(file)
            }else{
                this.recordFormFileList.pop()
                this.$message({
                    type: 'error',
                    message: '上传失败:'+response.error_message
                })
            }
        },
        recordFormEditFileUploadSuccess(response, file, fileList){
            if(response.status === 'success') {
                file.url = response.data.url
                this.recordFormEditFileList.push(file)
            }else{
                this.recordFormEditFileList.pop()
                this.$message({
                    type: 'error',
                    message: '上传失败:'+response.error_message
                })
            }
        },
        recordFormFileRemove(file, fileList){
            this.recordFormFileList = fileList
        },
        recordFormEditFileRemove(file, fileList){
            this.recordFormEditFileList = fileList
        },
        handleRecordEditForm(){
            let that = this
            let postUrl = '/api/tally-record/edit'
            let postData = JSON.parse(JSON.stringify(that.tallyRecordEditForm))
            let attachment = []
            that.recordFormEditFileList.forEach(v=>{
                attachment.push(v.url)
            });
            postData.tally_id = that.currentTallyId // 当前账本ID
            postData.tally_time = postData.dateR + ' '+ postData.timeR //拼账单时间
            postData.attachment = attachment.join(',')
            postData['category_id'] = this.categorys[this.categorys.length-1];
            postData['material_json'] = '';
            if(this.productListData.length > 0){
                postData['material_json'] = JSON.stringify(this.productListData);
            }

            axios.post(postUrl,postData,{
                headers: {'token': loginToken},
            }).then(function(res) {
                if(res.data.status === 'success'){
                    that.$message({
                        type: 'success',
                        message: '操作成功~'
                    });
                    that.recordFormEditFileList=[]
                    that.tallyRecordEditForm = {}
                    that.$emit('getRecordList')
                    that.$emit('modalClose')
                }else{
                    that.$message({
                        type: 'error',
                        message: '解析数据失败:'+res.data.error_message
                    })
                }
            })
        },
    }
})
</script>
